const autoEffectCycleType = [
  {
    type: '不重复',
    value: 0
  },
  {
    type: '按周',
    value: 1
  },
  {
    type: '自定义',
    value: 2
  }
];

const weekOpt = [
  {
    type: '周一',
    value: '2'
  },
  {
    type: '周二',
    value: '3'
  },
  {
    type: '周三',
    value: '4'
  },
  {
    type: '周四',
    value: '5'
  },
  {
    type: '周五',
    value: '6'
  },
  {
    type: '周六',
    value: '7'
  },
  {
    type: '周日',
    value: '1'
  }
];
import utils from '@/mixins/utils.js';
export default {
  name: 'addChaoXiChannel',
  mixins: [utils],
  data() {
    return {
      autoEffectCycleType,
      weekOpt,
      initTideChannelData: {
        autoChangeEnable: false,
        autoChangeType: 0,
        autoEffectCycleContent: {
          effectCycleArray: []
        },
        autoEffectCycleType: 0,
        autoEffectTimer: {
          effectTimerArray: []
        },
        effectInvalidStatus: 0,
        effectInvalidTime: '',
        enterChannelId: null,
        executeStatus: 0,
        leaveChannelId: null,
        manualChangeEnable: true,
        manualChangeType: 0,
        parkId: this.$route.query.parkId,
        tideName: '潮汐通道',
        tideType: '0', //潮汐通道类型(0:进出切换通道 1:同进出通道)
        id: null,
        uiOpt: {
          weekSelected: [],
          dateSelected: [],
          timeList: [
            {
              timeRang: ['', '']
            }
          ]
        }
      },
      enterChannelList: [],
      leaveChannelList: [],
      curType: 'manualChangeEnable'
    };
  },
  created() {
    // this.getChannelList();
    this.getEnterChannelList(true);
    this.getLeaveChannelList(true);
  },
  methods: {
    getChannelList() {
      API.fetchGet(`/operatorPark/byParkID/${this.$route.query.parkId}`).then(
        res => {
          res.data.forEach(item => {
            if (item.entranceType === 1) { //入口
              this.enterChannelList.push(item);
            }

            if (item.entranceType === 2) { //出口
              this.leaveChannelList.push(item);
            }
          });
        },
        err => {}
      );
    }, 
    // 获取可选的入口通道
    getEnterChannelList(flag){
      if(flag){
        let params = {
          parkID: this.$route.query.parkId,
          entranceType: 1
        };
        this.enterChannelList = []
        API.fetchGet('/operatorPark/tideChannel/findTideChannelByParkIDAndEntranceType',params).then(res=>{
          if(res.data){
            let data = res.data
            data.forEach(item => {
              this.enterChannelList.push(item);
            });
          }
        },err=>{
  
        })
      }
    },
    // 获取可选的出口通道
    getLeaveChannelList(flag){
      if(flag){
        let params = {
          parkID: this.$route.query.parkId,
          entranceType: 2
        };
        this.leaveChannelList = []
        API.fetchGet('/operatorPark/tideChannel/findTideChannelByParkIDAndEntranceType',params).then(res=>{
          if(res.data){
            let data = res.data
            data.forEach(item => {
              this.leaveChannelList.push(item);
            });
          }
        },err=>{
  
        })
      }
    },
    typeChange(val) {
      if (val === 'manualChangeEnable') {
        this.initTideChannelData.manualChangeEnable = true;
        this.initTideChannelData.autoChangeEnable = false;
      }

      if (val === 'autoChangeEnable') {
        this.initTideChannelData.autoChangeEnable = true;
        this.initTideChannelData.manualChangeEnable = false;
      }
    },
    addTime() {
      this.initTideChannelData.uiOpt.timeList.push({
        timeRang: ['', '']
      });
    },
    delTime(list, index) {
      list.splice(index, 1);
    },
    checkTime(val, item, index, timeList) {
      if (this.vaidEffectTimeArray(val[0], val, index, timeList)) {
        this.showToast('生效时段不可重合，请重设', 2, 1500);
        timeList.splice(index, 1, {
          timeRang: ['', '']
        });
      }
    },
    vaidEffectTimeArray(val, item, index, timeList) {
      const self = this;
      let isEffectTime = false;
      let curTime = this.getTime(val);
      const cur_time_item = item;

      timeList.some((item, cindex) => {
        if (cindex !== index) {
          const s_time = item.timeRang[0] ? self.getTime(item.timeRang[0]) : null;
          const e_time = item.timeRang[1] ? self.getTime(item.timeRang[1]) : null;
          if (s_time !== null && e_time !== null) {
            if (curTime >= s_time && curTime <= e_time) {
              isEffectTime = true;
              return true;
            } else if (cur_time_item[0] && cur_time_item[1] && self.getTime(cur_time_item[0]) < s_time && self.getTime(cur_time_item[1]) > e_time) {
              isEffectTime = true;
              return true;
            }
          }
        } else if (cur_time_item[0] && cur_time_item[1] && self.getTime(cur_time_item[0]) == self.getTime(cur_time_item[1])) {
          isEffectTime = true;
          return true;
        }
      });
      return isEffectTime;
    },
    getTime(time) {
      const d = new Date();
      return new Date([d.getFullYear(), d.getMonth() + 1, d.getDate()].join('/') + ' ' + time).getTime();
    },
    saveEdit() {
      const self = this;
      let saveData = JSON.parse(JSON.stringify(this.initTideChannelData));
      if (saveData.autoChangeEnable) {
        saveData.autoEffectTimer.effectTimerArray = [];
        saveData.uiOpt.timeList.forEach(item => {
          saveData.autoEffectTimer.effectTimerArray.push(item.timeRang.join('-'));
        });

        if (saveData.autoEffectCycleType === 0) {
          const d = new Date();
          saveData.autoEffectCycleContent.effectCycleArray = [];
          saveData.autoEffectCycleContent.effectCycleArray.push(`${d.getFullYear()}-${this.add0(d.getMonth() + 1)}-${this.add0(d.getDate())}`);
          saveData.uiOpt.timeList.some(item => {
            if (self.getTime(item.timeRang[0]) < d.getTime() - d.getMinutes() * 1000) {
              let next_day = d.getTime() + 1000 * 60 * 60 * 24;
              next_day = new Date(next_day);
              saveData.autoEffectCycleContent.effectCycleArray.push(`${next_day.getFullYear()}-${this.add0(next_day.getMonth() + 1)}-${this.add0(next_day.getDate())}`);
              return true;
            }
          });
        }

        if (saveData.autoEffectCycleType === 1) {
          saveData.autoEffectCycleContent.effectCycleArray = saveData.uiOpt.weekSelected;
        }

        if (saveData.autoEffectCycleType === 2) {
          saveData.autoEffectCycleContent.effectCycleArray = saveData.uiOpt.dateSelected;
        }
      }

      if (saveData.manualChangeEnable) {
        saveData.autoEffectTimer = null;
        saveData.autoEffectCycleContent = null;
      }

      if (saveData.autoChangeEnable) {
        saveData.autoEffectCycleContent = JSON.stringify(saveData.autoEffectCycleContent);
        saveData.autoEffectTimer = JSON.stringify(saveData.autoEffectTimer);
      }
      saveData.tideType = Number(saveData.tideType)

      API.fetchPost('/operatorPark/addParkCloudTideChannel', saveData).then(
        res => {
          if (res.status === 1) {
            this.showToast('新增潮汐通道成功', 1, 1500);
            setTimeout(() => {
              this.back();
            }, 1500);
          } else {
            this.showToast(res.message, 2, 1500);
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    testForm() {
      this.$refs['initTideChannelData'].validate(valid => {
        if (valid) {
          this.saveEdit();
        } else {
        }
      });
    },
    add0(number) {
      if (number.toString().length == 1) {
        return `0${number}`;
      } else {
        return number;
      }
    },
    back() {
      this.$router.push({
        name: 'tideChannelList',
        query: this.$route.query
      });
    }
  }
};
